package com.katze.common.zip;

import com.katze.common.Delete;
import com.katze.common.http.HttpUtils;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.file.Path;
import java.util.function.Consumer;
import java.util.function.Function;

public class ZipCompressHolder extends ZipCompressHandle<ZipCompressHolder> {
    private static final Logger log = LoggerFactory.getLogger(ZipCompressHolder.class);

    private ZipCompressHolder(){}

    /**
     * Zip压缩实例(第一个路径同级位置为默认输出文件路径)
     */
    public static ZipCompressHandle<ZipCompressHolder> builder() {
        return new ZipCompressHolder();
    }

    /**
     * 压缩目录
     */
    @Override
    public ZipCompressHolder execute() {
        try {
            long start = System.currentTimeMillis();
            this.scatter().writeTo(storage);
            log.debug("{} 目录已压缩完成, 总耗时: {} ms", targets, System.currentTimeMillis() - start);
        } catch (Throwable e) {
            log.error("compress fail: {}", targets, e);
        }
        return this;
    }

    /**
     * 查看所有压缩目录
     */
    public ZipCompressHolder peek(Consumer<Path> consumer) {
        for (Path item : targets) {
            consumer.accept(item);
        }
        return this;
    }

    public Delete<Boolean> download(HttpServletResponse response) {
        return HttpUtils.download(response).load(storage.toFile());
    }

    public Path toPath() {
        return storage;
    }

    public <T>T map(Function<Path, T> fun) {
        return fun.apply(storage);
    }
}
